package cn.itsource.pethome.system.fastdf.contrllor;

import cn.itsource.pethome.utils.AjaxResult;
import cn.itsource.pethome.utils.FastdfsUtil;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fast")
public class FstdfContrllor {
    /*文件上传*/
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            byte[] bytes = file.getBytes();
            String filename = file.getOriginalFilename();//上传文件的名字 全名  包括 后缀名
            String substring = filename.substring(filename.lastIndexOf(".") + 1);//包含了.的
            String uploadPath = FastdfsUtil.upload(bytes, substring);
            return AjaxResult.success().setData(uploadPath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常,请稍后再试");
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常,请稍后再试");
        }
    }


    /*文件删除*/
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String  path){
        try {
            /*传过来的参数*/
            //     /group1/M00/03/69/CgAIC2O5iU6AGRGXAAPIURq_oME841.jpg   前面那个/不能要
            //处理  group1/M00/03/69/CgAIC2O5iU6AGRGXAAPIURq_oME841.jpg
            String filePath = path.substring(1);
            //处理 group1
            String group = filePath.substring(0, filePath.indexOf("/"));
            //处理 /M00/03/69/CgAIC2O5iU6AGRGXAAPIURq_oME841.jpg
            String bodyPath = filePath.substring(filePath.lastIndexOf("/") + 1);
            System.out.println(group);
            System.out.println(bodyPath);
            FastdfsUtil.delete(group,path);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常,请稍后再试");
        }
    }
}
